import { useEffect, useMemo, useState } from "react";
import { Product } from "@/business.InterfaceLayer/type";
import useSortFilters from "../useSortFiltersQuery";

const useFilterProducts = (allProducts: Product[]) => {
  const { filters } = useSortFilters();
  const [filteredProducts, setFilteredProducts] = useState<Product[]>([]);

  useEffect(() => {
    let tempFilteredProducts = allProducts.slice(); // Создаем копию массива allProducts

    // Фильтрация по брендам
    if (filters.brands && filters.brands.length > 0) {
      tempFilteredProducts = tempFilteredProducts.filter((product: Product) =>
        filters.brands?.includes(product.brand)
      );
    }

    // Фильтрация по цветам
    if (filters.colors && filters.colors.length > 0) {
      tempFilteredProducts = tempFilteredProducts.filter((product: Product) =>
        filters.colors?.includes(product.colors)
      );
    }

    // Фильтрация по цене
    if (filters.price && filters.price.length === 2) {
      const [minPrice, maxPrice] = filters.price;
      tempFilteredProducts = tempFilteredProducts.filter(
        (product: Product) =>
          product.price >= Math.round(minPrice) &&
          Math.round(product.price) <= maxPrice
      );
    }

    // Сортировка
    switch (filters.sort) {
      case "price_asc":
        tempFilteredProducts.sort((a, b) => a.price - b.price);
        break;
      case "price_desc":
        tempFilteredProducts.sort((a, b) => b.price - a.price);
        break;
      case "id_asc":
        tempFilteredProducts.sort((a, b) => a.product_id - b.product_id);
        break;
      case "id_desc":
        tempFilteredProducts.sort((a, b) => b.product_id - a.product_id);
        break;
      default:
        break;
    }

    setFilteredProducts(tempFilteredProducts);
  }, [allProducts, filters]);

  return useMemo(() => filteredProducts, [filteredProducts]);
};

export default useFilterProducts;
